//
//  ECAudioPlayerView.m
//  Edu_iOS2018
//
//  Created by apple on 2018/3/13.
//  Copyright © 2018年 yanyan. All rights reserved.
//

// 图片路径
#define ZFPlayerSrcName(file)               [@"ZFPlayer.bundle" stringByAppendingPathComponent:file]

#define ZFPlayerFrameworkSrcName(file)      [@"Frameworks/ZFPlayer.framework/ZFPlayer.bundle" stringByAppendingPathComponent:file]

#define ZFPlayerImage(file)                 [UIImage imageNamed:ZFPlayerSrcName(file)] ? :[UIImage imageNamed:ZFPlayerFrameworkSrcName(file)]

#import "ECAudioPlayerView.h"
#import "SUPlayer.h"
#import "XTimer.h"
#import "ECUCatalogModel.h"

@interface ECAudioPlayerView()<UIGestureRecognizerDelegate>

///播放器背景
@property (nonatomic, strong) UIImageView *audioPlayerBackground;
///暂停按钮
@property (nonatomic, strong) UIButton *pauseBtn;
///播放进度条
@property (nonatomic, strong) UISlider *audioSlider;
///已播放时长
@property (nonatomic, strong) UILabel *playingTimeLab;
///总时长
@property (nonatomic, strong) UILabel *allTimeLab;
///音频是否播放
@property (nonatomic, assign) BOOL isPlaying;
///控制栏是否显示
@property (nonatomic, assign) BOOL isShowBottom;
///速率列表是否显示
@property (nonatomic, assign) BOOL isShowRateView;
///底部背景图
@property (nonatomic, strong) UIImageView *bottomImageView;
///头部背景图
@property (nonatomic, strong) UIImageView *topImageView;
/** 单击 */
@property (nonatomic, strong) UITapGestureRecognizer *singleTap;
///中部GIF图片
@property (nonatomic, strong) ECUButton *middleStatusBtn;
///速率选择按钮
@property (nonatomic, strong) UIButton *rateSelectBtn;
///速率选择底部view
@property (nonatomic, strong) UIView *rateBaseView;
///速率数组
@property (nonatomic, strong) NSArray *rateArr;
///计时器
@property (nonatomic, strong) XTimer *timer;
///重播使用url
@property (nonatomic, copy) NSString *localUrl;
///重播按钮
@property (nonatomic, strong) UIButton *replayBtn;

@end

@implementation ECAudioPlayerView

-(instancetype)init{
    self = [super init];
    if (self) {
        [self initAudioPlayer];
        [self loadPlay];
        [self createGesture];
        [self setTimeConfig];
        
    }
    return self;
}

-(void)setTimeConfig{
    //初始化计时器
    self.timer = [XTimer scheduledTimerWithTimeInterval:5 target:self selector:@selector(XTimerSelector) userInfo:nil repeats:YES];
}

-(void)loadPlay{
    
    //添加后台播放代码：
    AVAudioSession *session = [AVAudioSession sharedInstance];
    [session setActive:YES error:nil];
    [session setCategory:AVAudioSessionCategoryPlayback error:nil];
    
    //以及设置app支持接受远程控制事件代码。设置app支持接受远程控制事件，
    //其实就是在dock中可以显示应用程序图标，同时点击该图片时，打开app。
    //或者锁屏时，双击home键，屏幕上方出现应用程序播放控制按钮。
    [[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
    
    self.player = [[SUPlayer alloc]init];
    [self.player addObserver:self forKeyPath:@"progress" options:NSKeyValueObservingOptionNew context:nil];
    [self.player addObserver:self forKeyPath:@"duration" options:NSKeyValueObservingOptionNew context:nil];
    [self.player addObserver:self forKeyPath:@"cacheProgress" options:NSKeyValueObservingOptionNew context:nil];
    [self.player addObserver:self forKeyPath:@"status_audio" options:NSKeyValueObservingOptionNew context:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleInterreption:) name:AVAudioSessionInterruptionNotification object:[AVAudioSession sharedInstance]];
    
    
    self.localUrl = [[NSString alloc]init];
    
    [self.audioSlider addTarget:self action:@selector(changeProgress:) forControlEvents:UIControlEventTouchUpInside];
}

//点击cell掉用此方法
-(void)setUrlOfAudioPlayView:(NSString *)urlStr{
    [self.timer stop];
    
    
    NSURL * url = [NSURL URLWithString:urlStr];
    [self.player replaceItemWithURL:url];
    [self.player play];
    self.isPlaying = YES;
    self.isShowBottom = YES;
    [self.timer reStart];
    
    //显示控制进度条
    self.bottomImageView.alpha = 1.f;
    self.topImageView.alpha = 1.f;
    
    [self.replayBtn setHidden:YES];//隐藏重播按钮
    [self.middleStatusBtn setHidden:NO];//显示中部切换按钮
    
    //保存本地url,重播使用
    self.localUrl = urlStr;
    
    [self.middleStatusBtn setImage:[UIImage imageNamed:@"audio_playing"] forState:0];//切换对应的图片 下如
    [self.pauseBtn setImage:ZFPlayerImage(@"ZFPlayer_pause") forState:0];
}

-(void)initAudioPlayer{
    [self addSubview:self.audioPlayerBackground];
    [self.audioPlayerBackground addSubview:self.topImageView];
    [self.audioPlayerBackground addSubview:self.bottomImageView];
    [self.audioPlayerBackground addSubview:self.middleStatusBtn];
    [self.audioPlayerBackground addSubview:self.replayBtn];
    [self.audioPlayerBackground addSubview:self.rateSelectBtn];
    
    [self.bottomImageView addSubview:self.pauseBtn];
    [self.bottomImageView addSubview:self.audioSlider];
    [self.bottomImageView addSubview:self.playingTimeLab];
    [self.bottomImageView addSubview:self.allTimeLab];

    WeakSelf(weakSelf);
    [self.audioPlayerBackground mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(weakSelf.mas_top);
        make.left.equalTo(weakSelf.mas_left);
        make.right.equalTo(weakSelf.mas_right);
        make.height.equalTo(weakSelf.mas_height);
    }];
    
    [self.topImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.trailing.equalTo(weakSelf.audioPlayerBackground);
        make.top.equalTo(weakSelf.audioPlayerBackground.mas_top).offset(0);
        make.height.mas_equalTo(50);
    }];
    
    [self.bottomImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.trailing.equalTo(weakSelf.audioPlayerBackground);
        make.bottom.equalTo(weakSelf.audioPlayerBackground.mas_bottom).offset(0);
        make.height.mas_equalTo(50);
    }];
    
    [self.middleStatusBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.center.equalTo(weakSelf.audioPlayerBackground);
        make.height.and.width.mas_equalTo(kProportion_Width(128));
    }];
    
    [self.replayBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.center.equalTo(weakSelf.audioPlayerBackground);
        make.width.mas_equalTo(kProportion_Width(128));
        make.height.mas_equalTo(self.replayBtn.mas_width).multipliedBy(1.5);
    }];
    
    [self.rateSelectBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(weakSelf.middleStatusBtn);
        make.right.equalTo(weakSelf.audioPlayerBackground.mas_right).offset(-7);
        make.height.and.width.mas_equalTo(kProportion_Width(120));
    }];
    
    [self.pauseBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(weakSelf.audioPlayerBackground.mas_left).offset(10);
        make.bottom.equalTo(weakSelf.audioPlayerBackground.mas_bottom).offset(-5);
        make.height.and.width.offset(30);
    }];
    
    [self.playingTimeLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(weakSelf.pauseBtn.mas_centerY);
        make.left.equalTo(weakSelf.pauseBtn.mas_right).offset(5);
        make.width.offset(40);
        make.height.offset(20);
    }];
    
    [self.allTimeLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(weakSelf.pauseBtn.mas_centerY);
        make.right.equalTo(weakSelf.audioPlayerBackground.mas_right).offset(-10);
        make.width.equalTo(weakSelf.playingTimeLab.mas_width);
        make.height.equalTo(weakSelf.playingTimeLab.mas_height);
    }];
    
    [self.audioSlider mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(weakSelf.pauseBtn.mas_centerY);
        make.left.equalTo(weakSelf.playingTimeLab.mas_right).offset(5);
        make.right.equalTo(weakSelf.allTimeLab.mas_left).offset(-5);
    }];
}

- (void)changeProgress:(UISlider *)slider {
    float seekTime = self.player.duration * slider.value;
    [self.player seekToTime:seekTime];
}

- (NSString *)convertStringWithTime:(float)time {
    if (isnan(time)) time = 0.f;
    int min = time / 60.0;
    int sec = time - min * 60;
    NSString * minStr = min > 9 ? [NSString stringWithFormat:@"%d",min] : [NSString stringWithFormat:@"0%d",min];
    NSString * secStr = sec > 9 ? [NSString stringWithFormat:@"%d",sec] : [NSString stringWithFormat:@"0%d",sec];
    NSString * timeStr = [NSString stringWithFormat:@"%@:%@",minStr, secStr];
    return timeStr;
}

-(UILabel *)playingTimeLab{
    if (!_playingTimeLab) {
        _playingTimeLab = [[UILabel alloc]init];
        _playingTimeLab.textColor = [UIColor colorWithHexString:@"ffffff"];
        _playingTimeLab.font = [UIFont systemFontOfSize:12.f];
        _playingTimeLab.text = @"00:00";
        _playingTimeLab.textAlignment = NSTextAlignmentCenter;
    }
    return _playingTimeLab;
}

-(UILabel *)allTimeLab{
    if (!_allTimeLab) {
        _allTimeLab = [[UILabel alloc]init];
        _allTimeLab.textColor = [UIColor colorWithHexString:@"ffffff"];
        _allTimeLab.font = [UIFont systemFontOfSize:12.f];
        _allTimeLab.text = [self convertStringWithTime:self.player.duration];
        _allTimeLab.textAlignment = NSTextAlignmentCenter;
    }
    return _allTimeLab;
}

- (UIImageView *)bottomImageView {
    if (!_bottomImageView) {
        _bottomImageView = [[UIImageView alloc] init];
        _bottomImageView.userInteractionEnabled = YES;
        _bottomImageView.alpha = 1;
        _bottomImageView.image = ZFPlayerImage(@"ZFPlayer_bottom_shadow");
    }
    return _bottomImageView;
}

- (UIImageView *)topImageView {
    if (!_topImageView) {
        _topImageView = [[UIImageView alloc] init];
        _topImageView.userInteractionEnabled = YES;
        _topImageView.alpha = 1;
        _topImageView.image = ZFPlayerImage(@"ZFPlayer_top_shadow");
    }
    return _topImageView;
}

-(UIImageView *)audioPlayerBackground{
    if (!_audioPlayerBackground) {
        _audioPlayerBackground = [[UIImageView alloc]init];
        _audioPlayerBackground.image = [UIImage imageNamed:@"audio_bg"];
        _audioPlayerBackground.userInteractionEnabled = YES;
    }
    return _audioPlayerBackground;
}

-(ECUButton *)middleStatusBtn{
    if (!_middleStatusBtn) {
        _middleStatusBtn = [[ECUButton alloc]init];
        [_middleStatusBtn setImage:[UIImage imageNamed:@"audio_playing"] forState:0];
        [_middleStatusBtn addTarget:self action:@selector(pauseBtn_click:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _middleStatusBtn;
}

-(UIButton *)replayBtn{
    if (!_replayBtn) {
        _replayBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [_replayBtn setImage:ZFPlayerImage(@"ZFPlayer_repeat_video") forState:0];
        [_replayBtn addTarget:self action:@selector(middleStatusBtn_click) forControlEvents:UIControlEventTouchUpInside];
        _replayBtn.hidden = YES;
    }
    return _replayBtn;
}

-(UIButton *)rateSelectBtn{
    if (!_rateSelectBtn) {
        _rateSelectBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        _rateSelectBtn.backgroundColor = [UIColor colorWithHexString:@"#424242"];
        _rateSelectBtn.layer.masksToBounds = YES;
        _rateSelectBtn.layer.cornerRadius = kProportion_Width(120/2);
        [_rateSelectBtn setTitleColor:[UIColor whiteColor] forState:0];
        [_rateSelectBtn setTitle:@"1.0X" forState:0];
        _rateSelectBtn.titleLabel.font = [UIFont systemFontOfSize:14.f];
        [_rateSelectBtn addTarget:self action:@selector(rateSelectBtn_click:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _rateSelectBtn;
}

-(UIButton *)pauseBtn{
    if (!_pauseBtn) {
        _pauseBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [_pauseBtn addTarget:self action:@selector(pauseBtn_click:) forControlEvents:UIControlEventTouchUpInside];
        [_pauseBtn setImage:ZFPlayerImage(@"ZFPlayer_pause") forState:0];
    }
    return _pauseBtn;
}

-(UISlider *)audioSlider{
    if (!_audioSlider) {
        _audioSlider = [[UISlider alloc]init];
        _audioSlider.minimumTrackTintColor = [UIColor whiteColor];
        _audioSlider.maximumTrackTintColor = [UIColor colorWithHexString:@"#959495"];
        [_audioSlider setThumbImage:ZFPlayerImage(@"ZFPlayer_slider") forState:0];
    }
    return _audioSlider;
}

-(UIView *)rateBaseView{
    if (!_rateBaseView) {
        _rateBaseView = [[UIView alloc]init];
        [self.audioPlayerBackground addSubview:_rateBaseView];
        self.rateBaseView.backgroundColor = [[UIColor blackColor]colorWithAlphaComponent:0.5];
        
        WeakSelf(weakSelf);
        [_rateBaseView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.leading.trailing.equalTo(weakSelf.audioPlayerBackground);
            make.bottom.equalTo(weakSelf.audioPlayerBackground.mas_bottom).offset(0);
            make.height.mas_equalTo(kProportion_Width(300));
        }];
        [self updateConstraintsIfNeeded];
        
        self.rateArr = @[@"0.75",@"1.0",@"1.25",@"1.5",@"2.0"];
        for (int i = 0; i < 5; i++) {
            UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
            btn.frame = CGRectMake(kScreenWidth/5*i, kProportion_Width(75), kScreenWidth/5, kProportion_Width(175));
            [btn setTitleColor:[UIColor whiteColor] forState:0];
            btn.titleLabel.font = [UIFont systemFontOfSize:15.f];
            [btn setTitle:[NSString stringWithFormat:@"%@X",self.rateArr[i]] forState:0];
            btn.tag = 10 + i;
            [btn addTarget:self action:@selector(btn_click:) forControlEvents:UIControlEventTouchUpInside];
            [_rateBaseView addSubview:btn];
            
            if (i == 0) {//第一个btn中添加tiplab
                UILabel *tipLab = [[UILabel alloc]init];
                [_rateBaseView addSubview:tipLab];
                tipLab.frame = CGRectMake(0, 0, 40, 16);
                tipLab.centerY = btn.centerY - 30;
                tipLab.centerX = btn.centerX;
                tipLab.text = @"语速";
                tipLab.textColor = [UIColor colorWithHexString:@"#999999"];
                tipLab.font = [UIFont systemFontOfSize:15.f];
            }
            
        }
    }
    return _rateBaseView;
}

/**
 *  创建手势
 */
- (void)createGesture {
    // 单击
    self.singleTap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(singleTapAction:)];
    self.singleTap.delegate                = self;
    self.singleTap.numberOfTouchesRequired = 1; //手指数
    self.singleTap.numberOfTapsRequired    = 1;
    [self.audioPlayerBackground addGestureRecognizer:self.singleTap];
}

/**
 手势事件
 */
-(void)singleTapAction:(UIGestureRecognizer *) gesture{
    if (self.isShowRateView == YES) {
        self.rateBaseView.hidden = YES;
        self.isShowRateView = NO;
        return;
    }
    
    if (self.replayBtn.hidden == NO) {//重播按钮存在返回
        return;
    }
    
    if (self.isShowBottom == YES) {
        self.topImageView.alpha = 0;
        self.bottomImageView.alpha = 0;
        
        self.isShowBottom = NO;
        
        [self.timer stop];
        
    }else{
        self.topImageView.alpha = 1.f;
        self.bottomImageView.alpha = 1.f;
        
        self.isShowBottom = YES;
        
        [self.timer reStart];
    }
}

/**
 速率选择按钮
 */
-(void)rateSelectBtn_click:(UIButton *)btn{
    self.isShowRateView = YES;
    self.rateBaseView.hidden = NO;
    
    NSString *str = btn.titleLabel.text;
    
    for (id view in self.rateBaseView.subviews) {//寻找对应的view
        if ([view isKindOfClass:[UIButton class]]) {
            UIButton *selectBtn = (UIButton *)view;
            if ([selectBtn.titleLabel.text isEqualToString:str]) {
                [selectBtn setTitleColor:[UIColor colorWithHexString:@"#fc6721"] forState:0];
                
                UIImageView *imageView = [[UIImageView alloc]init];
                [selectBtn addSubview:imageView];
                [imageView mas_makeConstraints:^(MASConstraintMaker *make) {
                    make.centerY.equalTo(selectBtn.mas_centerY).offset(20);
                    make.centerX.equalTo(selectBtn.mas_centerX);
                    make.height.and.width.mas_equalTo(9);
                }];
                imageView.image = [UIImage imageNamed:@"audio_littleCricle"];//找到对应的btn 添加imageview
            }
        }
    }
}

/**
 速率选择列表按钮事件
 */
-(void)btn_click:(UIButton *)btn{
    
    self.isShowRateView = NO;
    self.rateBaseView.hidden = YES;
    
    if ([self.rateArr[btn.tag - 10] floatValue] == [self.rateSelectBtn.titleLabel.text floatValue]) {
        return;
    }
    [self.player setRate:[self.rateArr[btn.tag - 10] floatValue]];
    [self.rateSelectBtn setTitle:[NSString stringWithFormat:@"%@X",self.rateArr[btn.tag - 10]] forState:0];
    
    for (id view in self.rateBaseView.subviews) {//寻找对应的view
        if ([view isKindOfClass:[UIButton class]]) {
            UIButton *selectBtn = (UIButton *)view;
            [selectBtn setTitleColor:[UIColor whiteColor] forState:0];
            for (id image in selectBtn.subviews) {
                if ([image isKindOfClass:[UIImageView class]]){
                    [image removeFromSuperview];
                }
            }
        }
    }
}

-(void)XTimerSelector{
    [self.timer stop];
    if (self.isShowBottom == YES) {
        [UIView animateWithDuration:0.5 animations:^{//隐藏动画
            self.bottomImageView.alpha = 0;
            self.topImageView.alpha = 0;
        }];
        self.isShowBottom = NO;
    }else{//直接显示
        self.bottomImageView.alpha = 1;
        self.topImageView.alpha = 1;
        self.isShowBottom = YES;
    }
}

-(void)pauseBtn_click:(UIButton *)btn{//暂停按钮事件处理
    if (self.isPlaying == NO) {
        [self.player play];
        self.isPlaying = YES;
        [self.timer reStart];
        [self.middleStatusBtn setImage:[UIImage imageNamed:@"audio_playing"] forState:0];//切换对应的图片 下如
        [self.pauseBtn setImage:ZFPlayerImage(@"ZFPlayer_pause") forState:0];
    }else{
        [self.player pause];
        self.isPlaying = NO;
        [self.middleStatusBtn setImage:[UIImage imageNamed:@"audio_play"] forState:0];
        [self.pauseBtn setImage:ZFPlayerImage(@"ZFPlayer_play") forState:0];
    }
}

/**
 SUPlayerStateWaiting,
 SUPlayerStatePlaying,
 SUPlayerStatePaused,
 SUPlayerStateStopped,
 SUPlayerStateBuffering,
 SUPlayerStateError
 */
///监听播放状态
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context {
    if ([keyPath isEqualToString:@"progress"]) {
        if (self.audioSlider.state != UIControlStateHighlighted) {
            dispatch_async(dispatch_get_main_queue(), ^{
                self.audioSlider.value = self.player.progress;
                self.playingTimeLab.text = [self convertStringWithTime:self.player.duration * self.player.progress];
            });
        }
    }
    if ([keyPath isEqualToString:@"duration"]) {
        if (self.player.duration > 0) {
            self.allTimeLab.text = [self convertStringWithTime:self.player.duration];
            self.allTimeLab.hidden = NO;
            self.playingTimeLab.hidden = NO;
        }else {
            [self.pauseBtn setImage:ZFPlayerImage(@"ZFPlayer_pause") forState:0];
        }
    }
    if ([keyPath isEqualToString:@"cacheProgress"]) {
        //        NSLog(@"缓存进度：%f", self.player.cacheProgress);
    }
    if ([keyPath isEqualToString:@"status_audio"]) {//监听播放器的状态
        if ([[change valueForKey:NSKeyValueChangeNewKey]intValue] == 5 || [[change valueForKey:NSKeyValueChangeNewKey]intValue] == 3) {//播放失败/播放完成
            [self.replayBtn setHidden:NO];//重播按钮显示
            [self.middleStatusBtn setHidden:YES];//中间切换按钮隐藏
            [self.pauseBtn setImage:ZFPlayerImage(@"ZFPlayer_play") forState:0];
            self.topImageView.alpha = 0;
            self.bottomImageView.alpha = 0;
            
        }else if ([[change valueForKey:NSKeyValueChangeNewKey]intValue] == 1 || [[change valueForKey:NSKeyValueChangeNewKey]intValue] == 4) {
            
        }else if ([[change valueForKey:NSKeyValueChangeNewKey]intValue] == 2){
        }
        
        [[NSNotificationCenter defaultCenter]postNotificationName:kNotifactionAudioPlayingStatus object:nil userInfo:@{@"status_audio":[change valueForKey:NSKeyValueChangeNewKey]}];//音频播放界面 播放完成 发送该通知 给"详情页" 暂停定时器
    }
}

///播放完成后的重播按钮
-(void)middleStatusBtn_click{
    [self.replayBtn setHidden:YES];
    [self.middleStatusBtn setHidden:NO];
    
    self.topImageView.alpha = 1;
    self.bottomImageView.alpha = 1;
    
    self.isPlaying = YES;
    [self.timer reStart];
    
    [self.player replaceItemWithURL:[NSURL URLWithString:self.localUrl]];
    [self.player play];
    self.middleStatusBtn.userInteractionEnabled = NO;
    [self.middleStatusBtn setImage:[UIImage imageNamed:@"audio_playing"] forState:0];
    [self.pauseBtn setImage:ZFPlayerImage(@"ZFPlayer_pause") forState:0];
    
}

//处理中断事件
-(void)handleInterreption:(NSNotification *)sender{
    if(self.isPlaying){
        [self.player pause];
        self.isPlaying = NO;
    }else{
        [self.player play];
        self.isPlaying = YES;
    }
}

-(void)removeAudioPlayer{
    [self.player stop];
    [self removeFromSuperview];
}

@end
